package com.itheima.tlias84.filter;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.utils.JwtUtil;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Objects;

/**
 * 登录过滤器，进行登录token拦截
 *  这里的Filter 是 jakarta.servlet包下
 *
 *  init 方法，在过滤器初始化的时候调用
 */
@Slf4j
//@Component // 将过滤器注册到spring容器中

public class LoginFilter implements Filter {
    @Resource
    EmpMapper empMapper;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("开始执行http请求过滤");
        //参数向下转型成HttpServletRequest 以及 HttpServletResponse

        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
        //放行登录接口
        String requestURI = servletRequest1.getRequestURI();
     if (requestURI.contains("/login")){
         filterChain.doFilter(servletRequest,servletResponse);
         return;
     }
        //获取请求头中的token
        String token = servletRequest1.getHeader("token");
        //判断是否有token
        if(Objects.isNull(token)){
            writeErrorResponse( servletResponse1, "请先登录账号密码");
            return;
        }
        //使用jwt验证 token 验证token合法性
        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if(Objects.isNull(emp)|| ! emp.getPassword().equals(jsonObject.getString("password")))
            {
                writeErrorResponse(servletResponse1,"老老实实做人");
                return;
            }
        }catch (Exception e){
            writeErrorResponse( servletResponse1,"Token已过期");
            return;
        }

        //过滤链对象执行完过滤逻辑之后放行http请求，把request，response重新交给 controller（servlet）
       filterChain.doFilter(servletRequest,servletResponse);
        log.info("没了");
    }

    //设置给前端返回的参数
    private static void writeErrorResponse(HttpServletResponse servletResponse1,String msg) throws IOException {
        // 因为浏览器是UTF-8  如果不设置前端接受到的是？？？ 所以要设置UTF-8
        servletResponse1.setContentType("application/json;charset=UTF-8");
        servletResponse1.setCharacterEncoding("UTF-8");
        //设置响应状态码 加上这个必须要登录
        servletResponse1.setStatus(401);
        //因为前端是json格式的，所以这里要设置返回的格式为json 用JSONObject.toJSONString(fail)
        ResultUtil fail = ResultUtil.fail(msg);
        servletResponse1.getWriter().write(JSONObject.toJSONString(fail));
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
